import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isCollapse:false,
    token:'',
    tabsList:[
      {
        path:'/',
        name:'home',
        label:'首页',
        icon:'home'
      }
    ],
    currentMenu:null,
    menu:[]
  },
  getters: {
  },
  mutations: {
    CollapseMenu(state){
      state.isCollapse=!state.isCollapse
    },
    selectMenu(state,val){
      if(val.name!=='home'){
        state.currentMenu=val
        const result= state.tabsList.findIndex(item=>item.name===val.name)
        if(result==-1){
          state.tabsList.push(val)
        }else{
          state.currentMenu=null
        }
      }
    },
    closeTag(state,val){
      const result= state.tabsList.findIndex(item=>item.name==val.name)
      state.tabsList.splice(result,1)
    },
    setToken(state,val){
      state.token=val
      Cookie.set('token',val)
    },
    clearToken(state){
      state.token=''
      Cookie.remove('token')
    },
    getToken(state){
      state.token=state.token||Cookie.get('token')
    },
    setMenu(state,val){
      state.menu=val
      Cookie.set('menu',JSON.stringify(val))
    },
    clearMenu(state){
      state.menu=[]
      Cookie.remove('menu')
    },
    addMenu(state,router){
      if(!Cookie.get('menu')){
        return
      }

      const menu=JSON.parse(Cookie.get('menu'))
      state.menu=menu
      console.log('menu',menu)
      const menuArray=[]
      menu.forEach(item => {
        item.component=()=>import(`../views/${item.url}`)
        if(item.children){
          item.children.map(list=>{
            list.component= ()=> import(`../views/${list.url}`)
          })
        }
        menuArray.push(item)
      });

      /* 路由的动态添加 */
      menuArray.forEach(item=>{
        router.addRoute('Main',item)
        if( item.children && item.children.length ){
          item.children.forEach( list => {
            router.addRoute("Other", list)
          })
        } 
      })
    }
  },
  /* 这个路由要加缓存， 不然刷新页面路由调不到
  ok
  你先摸索一下，看知不知道怎么搞。不知道再问，早点睡觉去吧
  好 我关了
   */
  actions: {
  },
  modules: {
  }
})
